<template>
  <div>
    <!-- 面包导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 输入框部分 -->
          <!-- clearable表示可清空 -->
          <!-- clear表示点击重置 -->
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <!-- 按钮部分 -->
          <el-button type="primary" plain @click="addDialogVisable=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表数据 -->
      <el-table :data="userList" border stripe header-align="center">
        <!-- 给列添加type="index"就是加一个索引 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column align="center" prop="username" label="姓名"></el-table-column>
        <el-table-column align="center" prop="email" label="邮箱"></el-table-column>
        <el-table-column align="center" prop="mobile" label="电话"></el-table-column>
        <el-table-column align="center" prop="role_name" label="角色"></el-table-column>
        <el-table-column align="center" label="状态">
          <!-- 运用的是作用域插槽 -->
          <template slot-scope="scope">
            <!-- scope.row 的这个row是element底层封装好的 主要作用是：获取当前行的数据-->
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 编辑用户数据 -->
          <!-- 1、editUserHandle(scope.row)直接传递所有数据 -->
          <!-- 2、通过editUserHandle(scope.row.id)来传递发送请求的id -->
          <template slot-scope="scope">
            <el-button
              plain
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUserHandle(scope.row.id)"
            ></el-button>
            <el-button
              plain
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUserByID(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top">
              <el-button
                plain
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisable" width="30%" @close="resetForm">
      <!-- 弹框的主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 弹框的底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="addUser">添加</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的弹框 -->
    <el-dialog title="编辑用户信息" :visible.sync="editDialogVisible" width="30%" @close="editFormClose">
      <el-form ref="editUserRef" :model="userInfo" :rules="editUserRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSave">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="setRoleVisible" width="30%">
      <div>
        <p class="roleOpen">用户名称：{{userInfo.username}}</p>
        <p class="roleOpen">当前角色：{{userInfo.role_name}}</p>
        <p>
          分配角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data() {
    // 自定义表单验证邮箱手机号
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确规则的邮箱'))
    }
    const checkMobile = (rule, value, callback) => {
      const regEmail = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确规则的手机号'))
    }
    return {
      // 存储的是被选中的用户的Id
      selectedRoleId: '',
      // 存储的是用来展示弹出权限的数据
      userInfo: {},
      // 存储用户权限信息
      roleList: [],
      // 获取用户列表参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      // 存储用户信息的
      userList: [],
      // 用户总条目数
      total: 0,
      // 分配用户权限对话框可见性
      setRoleVisible: false,
      // 添加用户弹框
      addDialogVisable: false,
      // 编辑用户弹框的显示隐藏
      editDialogVisible: false,
      // 添加弹窗用户数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户数据的验证
      addFormRules: {
        // 对用户名进行验证
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        // 对密码进行验证
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '请输入正确的密码', trigger: 'blur' }
        ],
        // 对邮箱进行验证
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 对手机号进行验证
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 对弹出的编辑框进行验证
      editUserRules: {
        // 对邮箱进行验证
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 对手机号进行验证
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取用户列表数据的方法
    this.getUserList()
  },
  methods: {
    async setRoleHandle() {
      if (!this.selectedRoleId) {
        return this.$message.info('请选择权限')
      }
      const { data: res } = await this.$http.put(`/users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setRoleVisible = false
    },
    // 设置用户权限
    async setRole(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.roleList = res.data
      this.setRoleVisible = true
    },

    // 当点击删除按钮进行删除时
    async removeUserByID(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        // confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // catch是异常操作的捕获函数
      // err => { return err }箭头函数因为只返回err所以err=>err

      // 如果取消删除返回的结果是cancle
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了用户的删除')
      }
      // 执行删除 这里返回的结果是confirm
      const { data: res } = await this.$http.delete(`/users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 删除成功之后
      // 重新渲染数据
      this.getUserList()
    },
    // 当修改用户数据的弹窗关闭时重置表单数据
    editFormClose() {
      this.$refs.editUserRef.resetFields()
    },
    // 当点击确认修改按钮时，对表单数据进行预校验
    editSave() {
      this.$refs.editUserRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`/users/${this.userInfo.id}`, {
          mobile: this.userInfo.mobile,
          email: this.userInfo.email
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        // 当数据修改成功之后执行的步骤
        // 重新渲染数据
        // 弹出更新用户信息的提示信息
        // 关闭弹出的对话框
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.editDialogVisible = false
      })
    },
    // 编辑用户数据
    async editUserHandle(id) {
      // 方法一：直接传递所有的数据 参数为users
      // this.userInfo = users
      // console.log(this.userInfo)

      // 方法二、通过发起请求来获取数据 参数为id
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 将请求获得的数据存储到userInfo当中
      this.userInfo = res.data
      this.editDialogVisible = true
      console.log(this.userInfo)
    },
    // 点击添加按钮添加数据
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        // 弹框关闭的时候
        // 要刷新列表数据
        this.addDialogVisable = false
        this.getUserList()
      })
    },
    // 弹框关闭时，自动重置
    resetForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 当用户状态发生改变的时候触发的事件
    async userStateChange(userList) {
      const { data: res } = await this.$http.put(`/users/${userList.id}/state/${userList.mg_state}`)
      if (res.meta.status !== 200) {
        userList.mg_state = !userList.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 当pagenum改变时触发的事件
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getUserList()
    },
    // 当pagesize改变时侯触发的事件
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getUserList()
    },
    // 获取用户数据
    async getUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userList = res.data.users
      this.total = res.data.total
    }
  }
}
</script>

<style lang="less" scoped>
.roleOpen {
  margin: 20px 0px;
}
</style>
